#include "StdAfx.h"
#include "../Engine/BulletTriangleMeshConvert.hpp"
#include "../Engine/MapRenderer.hpp"
#include "../Engine/WorldPhysics.hpp"

namespace he
{
	WorldPhysics::WorldPhysics()
		: m_pBroadPhase(new btDbvtBroadphase()), m_pCollisionConf(new btDefaultCollisionConfiguration()), m_pCollisionDispatcher(new btCollisionDispatcher(m_pCollisionConf.get())),
		m_pPhysicsSolver(new btSequentialImpulseConstraintSolver()), m_pWorld(new btDiscreteDynamicsWorld(m_pCollisionDispatcher.get(), m_pBroadPhase.get(),
		m_pPhysicsSolver.get(), m_pCollisionConf.get())), m_pMapRenderer(nullptr)
	{
		m_pWorld->setGravity(btVector3(0,-9.81f,0));
	}

	WorldPhysics::~WorldPhysics()
	{
//		m_pWorld->removeRigidBody(m_pTankRigidBody.get());
		m_pWorld->removeRigidBody(m_pMapRigidBody.get());
	}

	void WorldPhysics::update(float Time)
	{
//		std::cout << "Time: " << Time << std::endl;
		m_pWorld->stepSimulation(Time, 500);

		btTransform trans;
//		m_pTankRigidBody->getMotionState()->getWorldTransform(trans);
//		std::cout << trans.getOrigin().getY() << std::endl;

	}

	void WorldPhysics::associate(he::MapRenderer *pMapRenderer)
	{
		m_pMapRenderer = pMapRenderer;
		// Convert
		he::MapRenderer::RenderOpVector_t const rop_vector = m_pMapRenderer->get_partitions_data();
		m_pMapTrimesh = he::BulletTriangleMeshConvert::convert(*rop_vector[0]->vertexData, *rop_vector[0]->indexData);

		m_pMapCollisionShape.reset(new btBvhTriangleMeshShape(m_pMapTrimesh.get(), true));
		m_pMapMotionState.reset(new btDefaultMotionState(btTransform(btQuaternion::getIdentity(), btVector3(0, 0,0))));
		btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, m_pMapMotionState.get(), m_pMapCollisionShape.get(), btVector3(0,0,0));
		m_pMapRigidBody.reset(new btRigidBody(groundRigidBodyCI));
		m_pWorld->addRigidBody(m_pMapRigidBody.get());

		
		
//		m_pWorld->addRigidBody(m_pTankRigidBody.get());
	}
} /*he*/
